package com.example.extract;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpMessage;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.AbstractHttpClient;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.example.common.CommonConst;
import com.example.model.Teacher;
import com.example.myutil.ClientManager;

public class ExtractTeacherInit {
	private List<Teacher> teachers;

	public ExtractTeacherInit() {
		teachers = new ArrayList<Teacher>();
	}

	public void initLoading() {
		try {
			String url = "http://121.248.70.214/jwweb/ZNPK/Private/List_JS.aspx?xnxq=20150&js=";
			HttpGet httpGet = ClientManager.getHttpGet(url);
			HttpResponse response = ClientManager.getResponse(httpGet);
			Header setCookie = response.getFirstHeader("Set-Cookie");
			String cookiename = setCookie.getName();
			String cookievalue = setCookie.getValue();
			CommonConst.cookie = cookiename + "=" + cookievalue.substring(0, cookievalue.indexOf(";"));
			System.out.println(CommonConst.cookie);
			if (response.getStatusLine().getStatusCode() == 200) {
				HttpEntity entity = response.getEntity();
				InputStream is = entity.getContent();
				parserAndStoreTeachers(is, "gb2312", url);
			}
			httpGet.releaseConnection();
			// storeData(elements, teachers);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void parserAndStoreTeachers(InputStream is, String characterset, String uri) throws IOException {
		File file = new File(CommonConst.initDataPath);
		if (!file.exists())
			file.createNewFile();
		FileOutputStream fos = new FileOutputStream(file);
		byte[] skip = "parent.theJS.innerHTML='".getBytes();
		is.read(skip, 0, skip.length);
		Document doc = Jsoup.parse(is, characterset, uri);
		System.out.println(doc.data());
		Elements elements = doc.select("select[name=Sel_JS] option[value^=000]");
		System.out.println(elements.size());
		Teacher teacher = null;
		for (Element element : elements) {
			teacher = new Teacher();
			teacher.setId(element.attr("value"));
			teacher.setName(element.text());
			teachers.add(teacher);
			fos.write(teacher.toString().getBytes());
		}
		fos.flush();
		fos.close();
	}

	public static void main(String[] args) {
		ExtractTeacherInit extractInit = new ExtractTeacherInit();
		extractInit.initLoading();
	}
}
